<script setup lang="ts">
  import {reactive,toRefs,computed} from 'vue';
  import type {App} from 'vue'

  interface Todo {
    id: number;
    content: string;
    completed: boolean;
  }

  interface State {
    current: Todo | null;
    content: String;
    todoList: Array<Todo>;
    filterStatus: string;
  }

  const state:State = reactive({
    filterStatus: 'all',
    current: null,
    content: '',
    todoList: [
      // {
      //   id: 1,
      //   content: 'vue.js',
      //   completed: true
      // },{
      //   id: 2,
      //   content: 'javaScript',
      //   completed: false
      // }
    ]
  })
  const {current,content,todoList} = {...toRefs(state)};
  // 新增任务数据
  function addData() {
    console.log('addData')
    // 1、文件框的输入数据 content
    const content = state.content.trim();
    // 2、判断数据是否为空，如果为空则不保存
    if(content.length === 0) return;
    // 3、如果不为空，则添加到数组中
    const id = state.todoList.length+1;
    state.todoList.push({
      id,
      content,
      completed: false
    })
    // 4、清空文本框内容
    state.content = '';
  }

  // 通过计算属性获取未完成的任务数
  const remaining = computed(() => state.todoList.filter(item => !item.completed).length)

  // 实现切换任务状态
  const toggleAll = computed({
    get() {
      return remaining.value === 0;
    },
    set(newVal) {
      console.log('toggleAll.newVal',newVal)
      state.todoList.forEach(item => item.completed = newVal)
    }
  })

  function removeData(index: number) {
    state.todoList.splice(index,1)
  }

  // 清除所有已完成任务
  function clearCompleted() {
    state.todoList = state.todoList.filter(item => !item.completed)
  }

  // 双击进入编辑状态
  function toEdit(item: Todo){
    state.current = item;
  }

  function cancelEdit() {
    state.current = null;
  }

  // 保存数据
  function finishEdit(item:Todo,index:number,event:any) {
    console.log(item,index,event)
    if(!state.current) return;
    state.current = null;
    const content = event.target.value.trim();
    if(!content) {
      removeData(index)
      return
    }
    item.content = content;
    state.current = null;
  }

  // 自定义局部指令：v-todo-focus 
  const vTodoFocus = {
    updated(el:any,binding:any) {
      console.log('vTodoFocus:binding.value',binding.value)
      if(binding.value){
        el.focus();
      }
    }
  }

  // 当hash值改变后会自动调用此方法
  window.onhashchange = function() {
    console.log('hash变化了',window.location.hash);
    const hash = window.location.hash.substring(2) || 'all';
    state.filterStatus = hash;
  }

  const x:any = null;
  window.onhashchange(x)

  // 定义一个计算属性 filterTodoList, 用于接收过滤出来的不同状态的任务数据
  const filterTodoList = computed(() => {
    const {filterStatus,todoList} = state;
    switch (filterStatus) {
      case 'active':
        return todoList.filter(item => !item.completed);
        break;
      case 'completed':
        return todoList.filter(item => item.completed);
        break;
      default:
        return todoList;
    }
  })
</script>

<template>
  <section class="todoapp">
    <header class="header">
      <h1>Vue3</h1>
      <input v-model.trim="content" @keyup.enter="addData" class="new-todo" placeholder="What needs to be done?" v-app-focus>
    </header>
    <!-- This section should be hidden by default and shown when there are todos -->
    <section class="main" v-show="todoList.length">
      <input v-model="toggleAll" id="toggle-all" class="toggle-all" type="checkbox">
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <!-- li有三种状态：未完成（没有样式）、已完成（completed）、编辑中（editing） -->
        <!-- {{ current }} -->
        <li v-for="(item,index) in todoList" :key="item.id" :class="{'completed': item.completed,'editing': current ===item}">
          <div class="view">
            <input class="toggle" type="checkbox" v-model="item.completed">
            <label @dblclick="toEdit(item)">{{ item.content }}</label>
            <button @click="removeData(index)" class="destroy"></button>
          </div>
          <input class="edit" v-todo-focus="current===item" :value="current?.content" @keyup.enter="$event.target?.blur()" @blur.stop="finishEdit(item,index,$event)" @keyup.esc="cancelEdit">
        </li>
      </ul>
    </section>
    <!-- This footer should be hidden by default and shown when there are todos -->
    <footer class="footer" v-show="todoList.length">
      <!-- This should be `0 items left` by default -->
      <span class="todo-count"><strong>{{ remaining }}</strong> item{{remaining===1?'':'s'}} left</span>
      <!-- Remove this if you don't implement routing -->
      <ul class="filters">
        <li>
          <a class="selected" href="#/">All</a>
        </li>
        <li>
          <a href="#/active">Active</a>
        </li>
        <li>
          <a href="#/completed">Completed</a>
        </li>
      </ul>
      <!-- Hidden if no completed items are left ↓ -->
      <button @click="clearCompleted" class="clear-completed">Clear completed</button>
    </footer>
  </section>
  <footer class="info">
    <p>Double-click to edit a todo</p>
    <!-- Remove the below line ↓ -->
    <p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
    <!-- Change this out with your name and url ↓ -->
    <p>Created by <a href="http://todomvc.com">you</a></p>
    <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
  </footer>
</template>

<style scoped></style>
